package cn.mhome.merchant.dao.spring.data.repository;

import java.util.Iterator;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Order;

public class PageableHelper {
	public static String getSqlExpressionForLimit(Pageable page) {
		if (page == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
        if(page.getPageNumber() != -1){
            sb.append("limit ");
            sb.append(page.getPageNumber()==0?0:(page.getPageNumber()-1) * page.getPageSize());
            sb.append(",");
            sb.append(page.getPageSize());
        }
		return sb.toString();
	}

	public static String getSqlExpressionForOrderBy(Pageable page) {
		if ((page == null) || (page.getSort() == null)) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		sb.append(" order by ");
		boolean isFirst = true;
		Iterator<Order> iterator = page.getSort().iterator();
		while (iterator.hasNext()) {
			Order order = iterator.next();
			if (isFirst == false) {
				sb.append(", ");
			} else {
				isFirst = false;
			}
			sb.append(order.getProperty());
			sb.append(" ");
			sb.append(order.getDirection().toString());
		}
		return sb.toString();
	}
}
